'''
Created on 2009-2-26

@author: zarra
'''



from sqlalchemy import  Column, Integer, String,Unicode,UnicodeText,Text
from sqlalchemy.orm import relation, backref,eagerload,sessionmaker,scoped_session
from lxml import etree

from model.expr_b._base import Base,expr_b
from model.expr_a._base import expr_a
from model.expr_a.department import Department



class Doctor(Base):
    __tablename__='expr_yhxx'
    
    id = Column('yh_id',String(16),primary_key=True)
    name=Column('yh_xm',Unicode(16),nullable=False)
    login_name=Column('yh_dlm',String(16),nullable=False)
    password=Column('yh_mm',String(16),nullable=False)
    is_del = Column('is_del',Integer,nullable=False)
    __permissions__=Column('yh_qx',Text)
    
    def __init__(self,name,login_name,password):
        self.name=name
        self.login_name=login_name
        self.password=password
    def __repr__(self):
        return "name:%s password:%s"%(self.name,self.password)
    @property
    def permissions(self):
        r=[]
        
        if self.__permissions__==None:
            return r
        
        
        #print self.__permissions__
        doc=etree.fromstring(self.__permissions__)
        s=expr_a()
        elements = doc.findall('yh_qx')
        ids = [ e.find('gzq_id').text for e in elements]
        r=s.query(Department).filter(Department.id.in_(ids)).order_by(Department.id).all()
        s.close()
        return r 
    
    def __json__(self):
        return {'name':self.name.strip()}
    


def find_doctor(d_id,password=None):
    if  isinstance(d_id,unicode):
        d_id=d_id
    if isinstance(password, unicode):
        password=password
    query=expr_b().query(Doctor).filter(Doctor.login_name==d_id).filter(Doctor.is_del !='1')
    if password != None:
        query=query.filter(Doctor.password == password)
    return query.first()

def find_department_id_by_name(name):
    print name,type(name)
    name=name
    print expr_a().query(Department).filter(Department.name == name)
    return expr_a().query(Department).filter(Department.name == name).filter(Department.is_del !='1').first()        